﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Security.Cryptography;
using CommModule.Security;

namespace CommModule.Messages
{
    public class SecureMessage: Convertible
    {
        private Object _object;
        private MessageSignature _messageSignature;

        public SecureMessage() { }

        public SecureMessage(Object obj, RSACryptoServiceProvider encryptor)
        {
            _object = obj;

            String objectString = ObjectSerialization.SerializeObjectAsString(_object);
            String hashedObject = Hash.GetStringHash(objectString);

            _messageSignature = new MessageSignature(hashedObject, encryptor);
        }

        public Object GetObject()
        {
            return _object;
        }

        public String GetTimestamp()
        {
            return _messageSignature.getTimestamp();
        }

        public Boolean ValidateMessage(String lastReceivedTS, RSACryptoServiceProvider remotePubKeyDecryptor)
        {
            if (_object == null)
                return false;

            String objectString = ObjectSerialization.SerializeObjectAsString(_object);
            String hashedObject = Hash.GetStringHash(objectString);

            return _messageSignature.validateSignature(hashedObject, "CERTCOP", "WEBSERVER", lastReceivedTS, remotePubKeyDecryptor);
        }
        
        public void ConvertToCanonic(XmlWriter xmlWriter)
        {
            xmlWriter.WriteStartElement("SecureMessage");

            if (_object != null)
            {
                XmlSerializationUtils.GetConversionObjectXml(_object, xmlWriter);
            }

            if (_messageSignature != null)
            {
                XmlSerializationUtils.GetConversionObjectXml(_messageSignature, xmlWriter);
            }

            xmlWriter.WriteEndElement();
        }

        public void ConvertFromCanonic(XmlTextReader xmlTextReader)
        {
            xmlTextReader.ReadStartElement();

            _object = XmlSerializationUtils.GetConversionXmlObject(xmlTextReader);

            _messageSignature = (MessageSignature)XmlSerializationUtils.GetConversionXmlObject(xmlTextReader);

            xmlTextReader.ReadEndElement();
        }
    }
}
